package com.tianyi.warehouse.service.impl;

import ch.qos.logback.core.db.dialect.DBUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.Db;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.entity.User;
import com.javaweb.system.service.IUserService;
import com.javaweb.system.utils.ShiroUtils;
import com.sphchina.esb.webservice.ISendToReviewLog;
import com.tianyi.warehouse.entity.DetailList;
import com.tianyi.warehouse.entity.OutboundCheck;
import com.tianyi.warehouse.entity.SaleOutReview;
import com.tianyi.warehouse.mapper.OutboundCheckMapper;
import com.tianyi.warehouse.service.IOutboundCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@Service
public class OutboundCheckServiceImpl extends BaseServiceImpl<OutboundCheckMapper, OutboundCheck> implements IOutboundCheckService {

    @Autowired
    OutboundCheckMapper outboundCheckMapper;

    @Autowired
    ISendToReviewLog sendToReviewLog;

    @Autowired
    IUserService userService;

    @Override
    public JsonResult saveOurboundCheck(String cgeneralbid,Integer checkuser) {
        if(StringUtils.isEmpty(cgeneralbid)){
            return JsonResult.error("出库复核明细主键不能为空");
        }
        OutboundCheck checkInfo=outboundCheckMapper.getCheckInfo(cgeneralbid);
        String secondCheck = "";
        if(checkInfo!=null && !StringUtils.isEmpty(checkInfo.getCheckUserName2())){
            //secondCheck = checkInfo.getCheckUserName2()+" "+DateUtil.format(checkInfo.getCheckTime2(), DateUtils.YYYY_MM_DD);
            secondCheck = checkInfo.getCheckUserName2();
        }
        //判断用户是否有效
        User user =  userService.getUser(checkuser);
        if(StringUtils.isNull(user)){
            return JsonResult.error("出库复核的用户ID【"+checkuser+"】无效");
        }

        String[] list= cgeneralbid.split(",",-1);
        OutboundCheck entity = null;
        Map<String,Object> param = new HashMap<>();
        SaleOutReview saleOutReview = new SaleOutReview();

        saleOutReview.setInitid("SaleOutReview");
        saleOutReview.setPk_org("1173");
        List<DetailList> detailLists = new ArrayList<>();
        try {
            for (String bid : list) {
                DetailList detailList = new DetailList();
                detailList.setCgeneralbid(bid);
                if(!StringUtils.isEmpty(secondCheck)){
                    //若复核用户1取消复核后再次复核，不能覆盖复核用户2的复核结果
                    detailList.setVbdef7(user.getRealname() +"/"+secondCheck);
                }else {
                    detailList.setVbdef7(user.getRealname());
                }
                detailLists.add(detailList);
            }
            saleOutReview.setDetailList(detailLists);
            JsonResult result= sendToReviewLog.callEsbKdl("SaleOutReview","", JSON.toJSONString(saleOutReview));
            if(result.getCode()>0){
                 return JsonResult.error(result.getMsg());
            }else {
                for (String bid : list) {
                    param.clear();
                    entity = new OutboundCheck();
                    entity.setCgeneralbid(bid);
                    entity.setCheckUser1(ShiroUtils.getUserId());
                    entity.setCheckTime1(DateUtils.now());
                    param.put("cgeneralbid", bid);
                    if (outboundCheckMapper.selectByMap(param).size() == 0) {
                        outboundCheckMapper.insert(entity);
                    }else{
                        UpdateWrapper<OutboundCheck> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.set("check_user1", checkuser).set("check_time1", DateUtils.now()).eq("cgeneralbid", bid);
                        outboundCheckMapper.update(new OutboundCheck(), updateWrapper);
                    }
                }
                return JsonResult.success();
            }
        }
        catch (Exception ex){
            return JsonResult.error(ex.getMessage());
        }


    }

    @Override
    public JsonResult cancelOurboundCheck(String cgeneralbid) {
        if(StringUtils.isEmpty(cgeneralbid)){
            return JsonResult.error("出库复核明细主键不能为空");
        }
        String[] list= cgeneralbid.split(",",-1);
        OutboundCheck entity = null;
        Map<String,Object> param = new HashMap<>();
        SaleOutReview saleOutReview = new SaleOutReview();

        saleOutReview.setInitid("SaleOutReview");
        saleOutReview.setPk_org("1173");
        List<DetailList> detailLists = new ArrayList<>();
        try {
            for (String bid : list) {
                DetailList detailList = new DetailList();
                detailList.setCgeneralbid(bid);
                OutboundCheck outboundCheck=outboundCheckMapper.getCheckInfo(bid);
                if(!StringUtils.isEmpty(outboundCheck.getCheckUserName2())){
                    detailList.setVbdef7(outboundCheck.getCheckUserName2());
                }else {
                    detailList.setVbdef7("");
                }
                detailLists.add(detailList);
            }
            saleOutReview.setDetailList(detailLists);
            JsonResult result= sendToReviewLog.callEsbKdl("SaleOutReview","", JSON.toJSONString(saleOutReview));
            if(result.getCode()>0){
                return JsonResult.error(result.getMsg());
            }else {
                for (String bid : list) {
                    UpdateWrapper<OutboundCheck> updateWrapper = new UpdateWrapper<>();
                    param.clear();
                    entity = new OutboundCheck();
                    entity.setCgeneralbid(bid);
                    entity.setCreateUser(ShiroUtils.getUserId());
                    entity.setCreateTime(DateUtils.now());
                    param.put("cgeneralbid", bid);
                    updateWrapper.set("check_user1", null).set("check_time1", null).eq("cgeneralbid", bid);
                    outboundCheckMapper.update(new OutboundCheck(), updateWrapper);
                }
                return JsonResult.success();
            }
        }
        catch (Exception ex){
            return JsonResult.error(ex.getMessage());
        }


    }

    @Override
    public JsonResult secondCheck(String cgeneralbid, Integer checkuser) {
        UpdateWrapper<OutboundCheck> updateWrapper = new UpdateWrapper<>();
        try{
            //判断用户是否有效
            User user =  userService.getUser(checkuser);
            if(StringUtils.isNull(user)){
                return JsonResult.error("出库复核的用户ID【"+checkuser+"】无效");
            }

            SaleOutReview saleOutReview = new SaleOutReview();

            saleOutReview.setInitid("SaleOutReview");
            saleOutReview.setPk_org("1173");
            List<DetailList> detailLists = new ArrayList<>();
            OutboundCheck entity=outboundCheckMapper.getCheckInfo(cgeneralbid);
            if(StringUtils.isNull(entity)){
                return JsonResult.error("无效的出库明细主键："+cgeneralbid);
            }
            if(StringUtils.isNotNull(entity.getCheckUser1()) && checkuser.equals(entity.getCheckUser1())){
                return JsonResult.error("复核人2不能与复核人1相同");
            }

            DetailList detailList = new DetailList();
            detailList.setVbdef7(entity.getCheckUserName1()+"/"+user.getRealname());
            detailList.setCgeneralbid(cgeneralbid);
            detailLists.add(detailList);
            saleOutReview.setDetailList(detailLists);
            JsonResult result= sendToReviewLog.callEsbKdl("SaleOutReview","", JSON.toJSONString(saleOutReview));
            if(result.getCode()>0){
                return JsonResult.error(result.getMsg());
            }else {
                updateWrapper.set("check_user2", checkuser).set("check_time2", DateUtils.now()).eq("cgeneralbid", cgeneralbid);
                outboundCheckMapper.update(new OutboundCheck(), updateWrapper);
                return JsonResult.success();
            }
        }
        catch(Exception ex){
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult cancelSecondCheck(String cgeneralbid, Integer checkuser) {
        UpdateWrapper<OutboundCheck> updateWrapper = new UpdateWrapper<>();
        try{
            //判断用户是否有效
            User user =  userService.getUser(checkuser);
            if(StringUtils.isNull(user)){
                return JsonResult.error("出库复核的用户ID【"+checkuser+"】无效");
            }

            SaleOutReview saleOutReview = new SaleOutReview();
            String[] list= cgeneralbid.split(",",-1);

            saleOutReview.setInitid("SaleOutReview");
            saleOutReview.setPk_org("1173");
            List<DetailList> detailLists = new ArrayList<>();
            for (String bid : list) {
                OutboundCheck entity=outboundCheckMapper.getCheckInfo(bid);
                if(StringUtils.isNull(entity)){
                    return JsonResult.error("无效的出库明细主键："+bid);
                }else{
                    if(!checkuser.equals(entity.getCheckUser2()) && !StringUtils.isNull(entity.getCheckUser2())){
                        return JsonResult.error("取消复核的操作人同已复核的操作人不一致："+cgeneralbid);
                    }
                }
                DetailList detailList = new DetailList();
                if (StringUtils.isEmpty(entity.getCheckUserName1())) {
                    detailList.setVbdef7("");
                } else {
                    detailList.setVbdef7(entity.getCheckUserName1());
                }
                detailList.setCgeneralbid(bid);
                detailLists.add(detailList);
            }
            saleOutReview.setDetailList(detailLists);
            JsonResult result= sendToReviewLog.callEsbKdl("SaleOutReview","", JSON.toJSONString(saleOutReview));
            if(result.getCode()>0){
                return JsonResult.error(result.getMsg());
            }else {
                for (String bid : list) {
                    updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("check_user2", null).set("check_time2", null).eq("cgeneralbid", bid);
                    outboundCheckMapper.update(new OutboundCheck(), updateWrapper);
                }
                return JsonResult.success();
            }
        }
        catch(Exception ex){
            return JsonResult.error(ex.getMessage());
        }
    }

}
